//
//  EyuPurchaseBridge.m
//  QySDKBridge
//
//  Created by lcc on 2025/2/10.
//

#import "EyuPurchaseBridge.h"
#import "EyuReportBridge.h"
#import <QySDKBridge/SDKBridgeUtil.h>
#import "EyuHeader.h"
#import "QyBaseEvent.h"
#import <EyuGameSDK/AboGameSDKApi.h>
#import "PurchaseProductInfo.h"
#import "SDKBridgeConstant.h"
@implementation EyuPurchaseBridge

+ (void)Purchase:(NSString *)purchaseData{
    NSLog(@"--->>> Purchase - purchaseDataString:%@", purchaseData);
    // json转字典
    NSDictionary* data = [SDKBridgeUtil JsonToDict:purchaseData];
    // 参数提取
    NSString* roleId = [EyuHeader Instance].m_UserId;
    NSString* roleName = [ROLE_NAME_PREFIX stringByAppendingString:[EyuHeader Instance].m_UserId];
    NSString* serverId = SERVER_ID;
    NSString* serverName = SERVER_NAME;
    NSString* roleLevel = ROLE_LEVEL;
    NSString* vipLevel = VIP_LEVEL;
    NSString* notifyUrl = @"";
    // 从Unity传递过来
    NSString* price = [data objectForKey:@"price"];
    NSString* cpOrderId = [data objectForKey:@"cpOrderId"];
    NSString* itemId = [data objectForKey:@"itemId"];
    NSString* itemName = [data objectForKey:@"itemName"];
    NSString* userId = [EyuHeader Instance].m_UserId;
    NSString* ext = [data objectForKey:@"ext"];
    [[AboGameSDKApi SDKManager]AppleInAppPurchaseWithRoleid:roleId rolename:roleName rolelevel:roleLevel serverid:serverId itemid:itemId cpOrderid:cpOrderId notify:notifyUrl cpext:ext money:price propName:itemName Success:^(NSDictionary* _Nonnull successBack){
        NSLog(@"EyuSDKBridge - Purchase Success! %@", successBack);
        [SDKBridgeUtil SendMsgToUnity:UnitySdkPurchaseSuccessFunc msg:itemId];
    } eyuFail:^(NSError* _Nonnull error){
        NSLog(@"EyuSDKBridge - Purchase Fail! %@", error);
        NSString * msg = [itemId stringByAppendingString:@"|"];
        NSMutableDictionary*payerror=[NSMutableDictionary dictionaryWithDictionary:error.userInfo];
        [payerror setObject:[NSNumber numberWithInteger:error.code==18014?11036:error.code] forKey:@"result"];
        NSString * json = [SDKBridgeUtil ObjectToJson:payerror];
        [SDKBridgeUtil SendMsgToUnity:UnitySdkPurchaseFailFunc msg:[msg stringByAppendingString:json]];
    }];
}

// type:0 -> 普通商品；1 -> 订阅商品
+ (void)QueryProducts:(NSString *)productList type:(int)type{
    NSLog(@"--->>> QueryProducts - productList:%@", productList);
    NSMutableArray * productArr = [SDKBridgeUtil JsonToArray:productList];
    NSLog(@"--->>> QueryProducts - productArr:%lu", productArr.count);
    NSMutableArray * queryArr = [NSMutableArray arrayWithArray:productArr];
    if ([EyuHeader Instance].m_ProductPriceDict.count > 0){
        for (int i = 0; i < productArr.count; i ++) {
            NSString * productId = productArr[i];
            if ([[EyuHeader Instance].m_ProductPriceDict objectForKey:productId]){
                [queryArr removeObject:productId]; // 已查询过，无需再次查询
            }
        }
    }
    
    NSLog(@"--->>> querySize:%lu", queryArr.count);
    if (queryArr.count == 0){ // 说明都查到了
        [EyuPurchaseBridge SendProductInfo2Unity:productArr];
        return;
    }
    [[AboGameSDKApi SDKManager]GameGetAppstoreProductsInfo:queryArr infoCall:^(int stateCode, NSDictionary * _Nonnull myProducts) {
        if (stateCode == 1){
            // 商品查询成功
            NSLog(@"--->>> 查询成功 - myProducts:%lu", myProducts.count);
            if (myProducts.count > 0){
                for (NSString * key in myProducts) {
                    NSString * price = [[EyuHeader Instance].m_ProductPriceDict objectForKey:key];
                    if (price == nil){
                        [[EyuHeader Instance].m_ProductPriceDict setObject:myProducts[key] forKey:key];
                        NSString * output = [NSString stringWithFormat:@"--->>> 首次查询成功 - productId:%@,price:%@", key, myProducts[key]];
                        NSLog(@"%@", output);
                    }
                }
            }
            
            [EyuPurchaseBridge SendProductInfo2Unity:productArr];
        }
        else{
            // 商品查询失败
        }
    }];
}

+ (void)SendProductInfo2Unity:(NSArray *)productList{
    NSLog(@"--->>> SendProductInfo2Unity - productList:%lu", productList.count);
    NSMutableArray * arr = [NSMutableArray array];
    for (int i = 0; i < productList.count; i++) {
        NSString * productId = productList[i];
        PurchaseProductInfo * info = [PurchaseProductInfo alloc];
        NSString * price = [[EyuHeader Instance].m_ProductPriceDict objectForKey:productId];
        info.productId = productId;
        info.name = [@"Product_" stringByAppendingString:productId];
        if (price != nil){
            info.price = price;
        }
        [arr addObject:[info toDictionary]];
    }
    
    NSLog(@"--->>> SendProductInfo2Unity - arr:%lu", arr.count);
    NSString * json = arr.count == 0 ? @"{}" : [SDKBridgeUtil ObjectToJson:arr];
    
    NSLog(@"--->>> SendProductInfo2Unity - json:%@", json);
    [SDKBridgeUtil SendMsgToUnity:UnitySdkPurchaseProductQueryFunc msg:json];
}
@end
